$(document).ready(function () {
    function setOrBindEmail(email) {
        let t1 = document.querySelector("#set-text-1");
        let t2 = document.querySelector("#set-text-2");
        if (email == "null" || email == null) {
            let set = document.querySelector("#set-form-valid");
            set.style.display = "none";
            t1.innerHTML = "";
            t1.append("绑定邮箱");
        } else {
            let set = document.querySelector("#set-form-valid");
            set.style.display = "display";
            $("#set-currentEmail").val(email);
            t1.innerHTML = "";
            t1.append("当前邮箱");
            t2.innerHTML = "";
            t2.append("新邮箱地址");
        }
    }

// 设置模态框控制
    $('#set-settingsBtn').click(function () {
        //初始化信息
        let path = "/head-portrait/" + localStorage.getItem("headPortrait");
        $('.set-current-avatar #set-head-portrait').attr('src', path);
        $('.set-form-group #set-username').attr('value', localStorage.getItem("userName"));
        $('.set-form-group #set-signature').val(localStorage.getItem("sign"));

        $('#set-settingsModal').addClass('active');
        setOrBindEmail(localStorage.getItem("email"));
    });

    $('#set-closeModal').click(function () {
        //重新获取用户信息
        getUserInfo();
        $('#set-settingsModal').removeClass('active');
    });

// 选项卡切换
    $('.set-tab-btn').click(function () {
        $('.set-tab-btn').removeClass('active');
        $(this).addClass('active');

        let tabId = $(this).data('tab');
        $('.set-tab-content').removeClass('active');
        $('#' + tabId).addClass('active');
    });

// 头像上传和裁剪
    let setCropper;

    $('#set-uploadTrigger').click(function () {
        $('#set-avatar-input').click();
    });

    $('#set-avatar-input').change(function (e) {
        if (e.target.files && e.target.files[0]) {
            let file = e.target.files[0];

            // 检查文件类型
            if (!file.type.match('image.*')) {
                setShowNotification('请选择图片文件！', 'error');
                return;
            }

            // 检查文件大小 (限制为5MB)
            if (file.size > 5 * 1024 * 1024) {
                setShowNotification('图片大小不能超过5MB！', 'error');
                return;
            }

            let reader = new FileReader();

            reader.onload = function (event) {
                $('#set-cropContainer').show();

                // 销毁现有的Cropper实例
                if (setCropper) {
                    setCropper.destroy();
                }

                // 创建新的Cropper实例
                let image = document.createElement('img');
                image.id = 'set-cropImage';
                image.src = event.target.result;
                image.style.maxWidth = '100%';

                $('#set-cropPreview').html(image);

                setCropper = new Cropper(image, {
                    aspectRatio: 1,
                    viewMode: 1,
                    guides: true,
                    autoCropArea: 0.8,
                });
            }

            reader.readAsDataURL(file);
        }
    });

// 确认裁剪
    $('#set-confirmCrop').click(function () {
        if (setCropper) {
            // 获取裁剪后的图片数据
            let croppedCanvas = setCropper.getCroppedCanvas({
                width: 300,
                height: 300
            });

            // 转换为DataURL
            let croppedImage = croppedCanvas.toDataURL('image/jpeg');

            // 更新预览
            $('.set-current-avatar img').attr('src', croppedImage);

            // 隐藏裁剪区域
            $('#set-cropContainer').hide();

            setShowNotification('头像已更新，请保存设置！');
        }
    });

// 取消裁剪
    $('#set-cancelCrop').click(function () {
        $('#set-cropContainer').hide();
        if (setCropper) {
            setCropper.destroy();
        }
    });
// 保存个人信息
    $('#set-saveProfile').click(function () {

        let userId = localStorage.getItem("userId");
        let userName = $('#set-username').val();
        if (userName == localStorage.getItem("userName")) userName = "";

        let sign = $('#set-signature').val();
        if (sign == localStorage.getItem("sign")) sign = "";

        let headPortrait = $('.set-current-avatar img').attr('src');
        if (headPortrait == "/head-portrait/" + localStorage.getItem("headPortrait")) headPortrait = "";
        // let headPortrait = setCropper;

        if (userName === "" && sign == "" && headPortrait == "") return;

        console.log("userId = " + userId + " userName = " + userName + " sign = " + sign);

        console.log(headPortrait);
        $.ajax({
            url: "set/set-user-info",
            type: "post",
            contentType: "application/json",
            data: JSON.stringify({
                userId: userId,
                userName: userName,
                sign: sign,
                headPortrait: headPortrait
            }),

            success: function (result) {
                if (result.data == "true") {
                    // 成功弹窗
                    setShowNotification('个人信息已成功更新！');
                } else {
                    setShowNotification(result.data);
                }
            },

            error: function (err) {
                if (err.status == 406) {
                    location.href = "login.html";
                    return;
                }
                console.log(result.message);
            }
        })
    });


// 保存密码
    $('#set-savePassword').click(function () {
        let currentPassword = $('#set-currentPassword').val();
        let newPassword = $('#set-newPassword').val();
        let confirmPassword = $('#set-confirmPassword').val();
        let userId = localStorage.getItem("userId");
        if (newPassword !== confirmPassword) {
            setShowNotification('两次输入的密码不一致！', 'error');
            return;
        }

        if (newPassword.length < 4) {
            setShowNotification('密码长度至少为4位！', 'error');
            return;
        }

        console.log("userId = " + userId + " currentPassword = " + currentPassword + " newPassword = " + newPassword);

        $.ajax(({
            url: "set/set-password",
            type: "post",
            contentType: "application/json",
            data: JSON.stringify({
                userId: userId,
                oldPassword: currentPassword,
                newPassword: newPassword
            }),

            success: function (result) {
                let data = result.data;
                if (data.status == "fail") {
                    setShowNotification(data.msg);
                    return;
                }
                setShowNotification("密码修改成功")
            },

            error: function (err) {
                if (err.status == 406) {
                    location.href = "login.html";
                    return;
                }
                console.log(result.message);
            }
        }));


        // 模拟成功
        $('#set-currentPassword, #set-newPassword, #set-confirmPassword').val('');
    });

// 保存邮箱
    $('#set-saveEmail').click(function () {
        let newEmail = $('#set-newEmail').val();
        let verifyCode = $('#set-verificationCode').val();

        if (localStorage.getItem("email") == null || localStorage.getItem("email") == "null") {
            newEmail = $('#set-currentEmail').val()
        }

        if (!setValidateEmail(newEmail)) {
            setShowNotification('请输入有效的邮箱地址！', 'error');
            return;
        }

        if (verifyCode != localStorage.getItem("verifyCode")) {
            setShowNotification('验证码错误！', 'error');
            return;
        }


        $.ajax({
            url: "set/set-email",
            type: "post",
            contentType: "application/json",
            data: JSON.stringify({
                userId: localStorage.getItem("userId"),
                oldEmail: localStorage.getItem("email"),
                email: newEmail
            }),
            success: function (result) {
                let data = result.data;
                if (data.status == 'fail') {
                    setShowNotification("邮箱跟新失败：" + data.msg, 'erroe');
                    return;
                }
                setShowNotification('邮箱已成功更新！');
                $('#set-currentEmail').val(newEmail);
                $('#set-verificationCode').val("");
            },

        });

        $('#set-newEmail, #set-emailPassword').val('');
    });


// 发送验证码功能
    $('#set-sendCode').click(function () {
        const email = $('#set-currentEmail').val();

        // 验证邮箱格式
        if (!setValidateEmail(email)) {
            setShowNotification('请输入有效的邮箱地址！', 'error');
            return;
        }


        // 禁用按钮，防止重复发送
        $(this).prop('disabled', true);
        let countdown = 60;
        const btn = $(this);
        btn.text(`${countdown}秒后重发`);

        // 倒计时
        const timer = setInterval(function () {
            countdown--;
            if (countdown <= 0) {
                clearInterval(timer);
                btn.prop('disabled', false);
                btn.text('发送验证码');
            } else {
                btn.text(`${countdown}秒后重发`);
            }

        }, 1000);

        // 发送AJAX请求到后端发送验证码
        $.ajax({
            url: 'verify/getEmailCode',
            type: 'POST',
            contentType: "application/json",
            data: JSON.stringify({
                userId: localStorage.getItem("userId"),
                userName: localStorage.getItem("userName"),
                email: email
            }),

            success: function (response) {
                let data = response.data;
                if (data.status == "fail") {
                    setShowNotification('获取验证码错误' + data.msg, 'error');
                    return;
                }
                localStorage.setItem("verifyCode", data.code);
                setShowNotification('验证码已发送，请查收！');
            },
            error: function () {
                setShowNotification('发送验证码失败，请重试！', 'error');
                // 出错时清除倒计时
                clearInterval(timer);
                btn.prop('disabled', false);
                btn.text('发送验证码');
            }
        });
    });

// 注销
    $('#log-off').click(function () {
        localStorage.removeItem("userName");
        localStorage.removeItem("userId");
        localStorage.removeItem("email");
        localStorage.removeItem("sign");
        localStorage.removeItem("headPortrait");
        deleteCookie1("jwt-token");
        location.assign("/login.html")
    });

    function setValidateEmail(email) {
        let re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        return re.test(String(email).toLowerCase());
    }
});

function deleteCookie1(name) {
    document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`;
    console.log("删除cookie");
}


setTimeout(function () {
$('#set-currentPassword').val('');
$('#search-input').val('');
}, 1000);


//删除填充的
$(document).ready(function () {
// 延迟一小段时间再清除，确保在浏览器自动填充之后执行
setTimeout(function () {
    $('#set-currentPassword').val('');
    $('#search-input').val('');
}, 1000);

});
